package com.yeskery.nut.extend.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * 结果集分裂器
 * @author YESKERY
 * 2024/8/29
 */
public class ResultSetSpliterator<T> implements Spliterator<T> {

    /** 结果集对象 */
    private final ResultSet resultSet;

    /** 结果集回调对象 */
    private final ResultSetRowCallback<T> callback;

    /**
     * 构建结果集分裂器
     * @param resultSet 结果集对象
     * @param callback 结果集回调对象
     */
    public ResultSetSpliterator(ResultSet resultSet, ResultSetRowCallback<T> callback) {
        this.resultSet = resultSet;
        this.callback = callback;
    }

    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            if (resultSet.next()) {
                action.accept(callback.callback(resultSet));
                return true;
            }
            return false;
        } catch (SQLException e) {
            throw new DataAccessException("JDBC SQL Execute Fail.", e);
        }
    }

    @Override
    public Spliterator<T> trySplit() {
        return null;
    }

    @Override
    public long estimateSize() {
        return Long.MAX_VALUE;
    }

    @Override
    public int characteristics() {
        return Spliterator.ORDERED;
    }

    /**
     * 生成Stream流
     * @return Stream流
     */
    public Stream<T> stream() {
        return StreamSupport.stream(this, false);
    }
}
